package com.biz.extenddemo.sso.service.Impl;

import com.lubase.core.model.SelectUserModel;
import com.lubase.core.model.UserInfoModel;
import com.lubase.core.service.UserInfoService;
import com.lubase.core.service.userright.UserRightService;
import com.lubase.orm.exception.InvokeCommonException;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.orm.model.LoginUser;
import com.biz.extenddemo.sso.service.SSOUserService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SSOUserServiceImpl implements SSOUserService {

    @Autowired
    UserRightService userRightService;

    @Autowired
    UserInfoService userInfoService;

    @SneakyThrows
    @Override
    public LoginUser getSSOUser(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        // 根据token获取用户信息
        String userCode = getUserCodeByToken(token);
        if (StringUtils.isEmpty(userCode)) {
            return null;
        }
        // 根据工号获取lubase系统欸用户信息
        UserInfoModel userInfoModel = userInfoService.getUserInfo(userCode);
        if (userInfoModel == null) {
            // 如果用户不存在，则创建用户
            List<SelectUserModel> list = new ArrayList<>();
            list.add(getUserModelByToken(token));
            // 创建用户
            userInfoService.createUser(list);
            // 创建用户再次获取用户信息
            userInfoModel = userInfoService.getUserInfo(userCode);
            if (userInfoModel == null) {
                throw new WarnCommonException("获取用户信息异常，请重试");
            }
        }
        if (!userInfoModel.isEnableTag()) {
            throw new InvokeCommonException("账号已经被禁用，请联系管理员");
        }
        LoginUser user = new LoginUser();
        user.setId(userInfoModel.getId());
        user.setCode(userInfoModel.getUserCode());
        user.setName(userInfoModel.getUserName());

        // 设置用户权限，并创建系统内token
        this.userRightService.getUserRight(user.getId());
        user.setToken(userInfoService.createUserToken(user));
        return user;
    }


    private String getUserCodeByToken(String token) {
        // 根据token的校验逻辑获取用户信息
        // 此处具体逻辑省略，私有部署后根据自己的逻辑来做处理

        // 这里写死返回值
        return "admin2";
    }

    private SelectUserModel getUserModelByToken(String token) {
        // 根据token的校验逻辑获取用户信息
        // 此处具体逻辑省略，私有部署后根据自己的逻辑来做处理

        // 这里写死返回值
        return new SelectUserModel();
    }
}
